package com.zf.zfed.audit.utils

import android.app.Activity
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.EditText
import java.util.*


/**
 * @author: wuqiqi
 * @date: 2024/5/16
 * @description: 编辑框焦点工具类
 */
class EditTextFocusUtils {
    companion object {

        /**
         * 去除编辑框的所有焦点
         */
        fun clearAllEditTextFocus(editTextList: Array<EditText>) {
            if (Objects.isNull(editTextList) || editTextList.size == 0) {
                return
            }
            for (editText in editTextList) {
                editText.isEnabled = false
                //editText.clearFocus()
            }
            for (editText in editTextList) {
                editText.isEnabled = true
                editText.clearFocus()
            }
        }

        /**
         * 处理EditText焦点和软键盘状态的公共方法
         *
         * @param editTextList 要处理的EditText列表
         */
        fun handleEditTextFocusAndKeyboardState(editTextList: Array<EditText>) {
            if (Objects.isNull(editTextList) || editTextList.size == 0) {
                return
            }
            // 获取根视图
            val rootView = (editTextList[0].context as Activity).window.decorView.rootView

            // 添加全局布局监听器
            rootView.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    // 检查软键盘状态
                    if (isKeyboardClosed(rootView)) {
                        // 软键盘关闭时，清除所有EditText的焦点
                        for (editText in editTextList) {
                            editText.clearFocus()
                        }
                        // 移除监听器
                        rootView.viewTreeObserver.removeOnGlobalLayoutListener(this)
                    }
                }
            })
        }


        /**
         * 检查软键盘是否关闭
         *
         * @param rootView 根视图
         * @return 如果软键盘关闭返回true，否则返回false
         */
        private fun isKeyboardClosed(rootView: View): Boolean {
            val screenHeight = rootView.rootView.height
            val visibleHeight: Int = getVisibleHeight(rootView)
            return screenHeight == visibleHeight
        }

        /**
         * 获取视图的可见高度
         *
         * @param view 要检查的视图
         * @return 视图的可见高度
         */
        private fun getVisibleHeight(view: View): Int {
            val location = IntArray(2)
            view.getLocationOnScreen(location)
            return location[1] + view.height
        }

    }
}